

let cors = require("cors")
let express = require("express")
let fs = require("fs")
let os = require("os");
let path = require("path")
let homedir = os.homedir()
let worldDir = path.resolve(homedir, "./AppData/Roaming/7DaysToDie/GeneratedWorlds")

let maps;

function updateMap() {
    if (fs.existsSync(worldDir)) {
        let cust_worlds = fs.readdirSync(worldDir)
        cust_worlds = cust_worlds.map(v => {
            let worldName = v;
            let dirPath = path.resolve(worldDir,"./" + worldName)
            let stats = fs.statSync(dirPath)
            return {
                name: worldName,
                path: dirPath,
                ctime: stats.ctime
            }
        })
        cust_worlds = cust_worlds.sort((b,a) => a.ctime - b.ctime)
    
        maps = cust_worlds
    
    }
}

updateMap()

// 打包指令 pkg -t win index.js
// html 代码混淆 https://jshunxiao.com/
let open = require("child_process")

const app = express()
// const sharp = require('sharp');
app.use(cors());
app.use(express.static('public'))

app.get('/api/getMaps', async (req, res) => {
    updateMap()
    res.send({maps}) 
})

app.get('/api/getBuilds', async (req, res) => {
    updateMap()
    let { path } = req.query;
    let pathfile = path + "/prefabs.xml";
    let mapinfo = path + "/map_info.xml";
    let pathimg = path + "/biomes.png";
    try {
        let str = fs.readFileSync(pathfile).toString()
        let mapstr = fs.readFileSync(mapinfo).toString()
        if (/property\s*name="HeightMapSize"\s*value="(\d+),(\d+)"/.test(mapstr)){
            let mapx = RegExp.$1;
            let mapy = RegExp.$2;


            fs.copyFileSync(pathimg, "./public/biomes.png")
            res.send({str:str, px: mapx, maps}) 

            // console.log(mapx, mapy);
            // sharp(pathimg)
            // .resize(mapx - 0, mapy - 0)
            // .toFile("./public/biomes.png")
            // .then(function(new_file_info) {
            //     res.send(str) 
            // })
            // .catch(function(err) {
            //     console.log("发生错误：", err);
            // });

        } else {
            
        }
        // fs.copyFileSync(pathimg, "./public/biomes.png")
        // res.send(str) 
    } catch (error) {
        
    }
})


app.listen(7643, () => {
    console.log("在浏览器中打开网址:http://localhost:7643")
    console.log("将包含biomes.png和prefabs.xml的存档路径(一般在C:/用户/你的用户名/AppData/Roaming/7DaysToDie/GeneratedWorlds/下)填写在对应本地网址的输入框内按回车")
    open.exec("start http://localhost:7643")
})

